package com.acme.team03.net.server;

import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.acme.team03.messages.Message;
import com.acme.team03.messages.TextMessage;
import com.acme.team03.net.Connection;
import com.acme.team03.net.MessageHandler;

public class ConnectionDispatcher {

	List<Connection> connections;
	private ExecutorService threadPool;

	public ConnectionDispatcher() {
		connections = new ArrayList<>();
		threadPool = Executors.newFixedThreadPool(1000);
	}

	public void establishConnection(Socket clientSocket,
			MessageHandler msgHandler) throws IOException {
		establishConnection(-1, clientSocket, msgHandler);
	}

	public void establishConnection(int id, Socket clientSocket,
			MessageHandler msgHandler) throws IOException {
		Connection conn = new Connection(id, clientSocket, msgHandler);
		if (id < 0) {
			Message msg;
			msg = conn.receiveMessage();
			conn.setID((int) msg.getProperty("ID"));
		} else {
			TextMessage msg = new TextMessage("");
			msg.setProperty("ID", id);
			conn.sendMessage(msg);
		}
		System.out.println("connection established");
		connections.add(conn);
		threadPool.execute(conn);
	}

	public List<Connection> getAllConnections() {
		return Collections.unmodifiableList(connections);
	}

	public void closeAllConnections() {
		for (Connection connection : getAllConnections()) {
			connection.close();
		}

	}

	public void sendAll(Message msg) throws IOException {
		for (Connection conn : getAllConnections()) {
			conn.sendMessage(msg);
		}
	}
}
